//
//  HACNodesComponentTecs.m
//  Pods
//
//  Created by silver on 2018/10/13.
//
//

#import "HACNodesComponentTecs.h"
#import "HACTecNode.h"

NSString *HACNodesComponentMainNodeKey = @"mainnode";
NSString *HACNodesComponentTecNodeKey = @"tecnode";
static CGFloat kMarginX = 7.0;
static CGFloat kMarginY = 4.0;
static CGFloat kSpaing = 4.0;
static CGFloat kTecBarHeight = 24.0;
static CGFloat kTecButtonWidth = 50.0;
#define kButtonImageName @"market_index_arrow"
#define kButtonTitleFont 12.0
#define kBarInfoFont 10.0
@implementation HACTecInfoBar
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _titleButton = [[UIButton alloc] initWithFrame:CGRectMake(kMarginX, kMarginY, kTecButtonWidth, frame.size.height - 2*kMarginY)];
        [_titleButton setTitleColor:RGB_HEX(kDefaultTextColor) forState:UIControlStateNormal];
        _titleButton.titleLabel.font = [UIFont systemFontOfSize:kButtonTitleFont];
        [_titleButton setImage:[UIImage imageNamed:kButtonImageName] forState:UIControlStateNormal];
        [self addSubview:_titleButton];
        _infoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _infoLabel.adjustsFontSizeToFitWidth = YES;
        [self addSubview:_infoLabel];
    }
    return self;
}
- (void)setInfoString:(NSAttributedString *)infoString {
    _infoString = infoString;
    if (infoString && infoString.length > 0) {
        self.infoLabel.attributedText = infoString;
    }
}
- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    self.titleButton.frame = CGRectMake(kMarginX, kMarginY, kTecButtonWidth, frame.size.height - 2*kMarginY);
    self.infoLabel.frame = CGRectMake(CGRectGetMaxX(self.titleButton.frame)+kSpaing, kMarginY, self.frame.size.width - self.titleButton.frame.size.width - kSpaing, frame.size.height - 2*kMarginY);
}
@end
@implementation HACNodesComponentTecs {
    NSMutableDictionary<NSNumber*, NSArray<NSNumber*>*> *_tecParamDic;//指标参数
}

@dynamic delegate;

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.orderSwitchTecNodeTypes = @[@(HACTecTypeVolume)
                                         ,@(HACTecTypeMACD)
                                         ,@(HACTecTypeKDJ)
                                         ,@(HACTecTypeRSI)
                                         ];
        _tecParamDic = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)setTecNodeTypes:(NSArray<NSNumber*> *)tecNodeTypes {
    _tecNodeTypes = tecNodeTypes;
    if (!self.tecBars && tecNodeTypes) {
        self.tecBars = [NSMutableArray arrayWithCapacity:tecNodeTypes.count];
    }
    int i = 0;
    for (; i < tecNodeTypes.count; i++) {
        NSString *nodeKey = [NSString stringWithFormat:@"%@%d", HACNodesComponentTecNodeKey, i];
        HACTecNode *tecNode = (HACTecNode *)[self.nodeDic objectForKey:nodeKey];
        HACTecType nodeType = (HACTecType)tecNodeTypes[i].integerValue;
        NSArray *tecParam = _tecParamDic[@(nodeType)];
        if (tecNode) {
            if (tecNode.tecType != nodeType) {
                [tecNode setTecType:nodeType];
            }
        } else {
            HACChartNode *mainNode = [self.nodeDic objectForKey:HACNodesComponentMainNodeKey];
            tecNode = [[HACTecNode alloc] initWithHostLayer:self.layer tecType:nodeType];
            tecNode.itemsSpace = 2;
            [tecNode setData:self.data];
            if (mainNode) {
                tecNode.visualCount = mainNode.visualCount;
                tecNode.relativeFrame = mainNode.relativeFrame;
                tecNode.pointRect = mainNode.pointRect;
                tecNode.startIndex = mainNode.startIndex;
                tecNode.endIndex = mainNode.endIndex;
            } else {
                tecNode.visualCount = self.visualCount;
            }
            [self.nodeDic setObject:tecNode forKey:nodeKey];
        }
        if (tecParam.count > 0) {
            [tecNode setTec:nodeType withParam:tecParam];
        }
        HACTecInfoBar *tecbar;
        if (i < self.tecBars.count) {
            tecbar = [self.tecBars objectAtIndex:i];
        }
        if (tecbar) {
            [self updateTecBar:tecbar withType:nodeType];
        } else {
            tecbar = [self createTecBarWithTecType:nodeType];
            [self addSubview:tecbar];
            [self.tecBars addObject:tecbar];
        }
        tecbar.titleButton.tag = i;
    }
    // remove tecbar
    if (i < self.tecBars.count) {
        NSUInteger sum = self.tecBars.count;
        for (NSUInteger j = sum-1; j >= i; j--) {
            HACTecInfoBar *tecbar = self.tecBars[j];
            [tecbar removeFromSuperview];
            [self.tecBars removeObject:tecbar];
        }
    }
    // remove tecnode
    long count = self.nodeDic.count;
    if (i < count - 1) {
        for (; i < count - 1; i++) {
            NSString *nodeKey = [NSString stringWithFormat:@"%@%d", HACNodesComponentTecNodeKey, i];
            HACChartNode *tecNode = [self.nodeDic objectForKey:nodeKey];
            [self.nodeDic removeObjectForKey:nodeKey];
            [tecNode removeNode];
        }
    }
}

- (void)setOrderSwitchTecNodeTypes:(NSArray<NSNumber *> *)orderSwitchTecNodeTypes{
    [self setOrderSwitchTecNodeTypes:orderSwitchTecNodeTypes showTecBtn:YES];
}

- (void)setOrderSwitchTecNodeTypes:(NSArray<NSNumber *> *)orderSwitchTecNodeTypes showTecBtn:(BOOL)showBtn {
    _orderSwitchTecNodeTypes = orderSwitchTecNodeTypes;
    UIImage *image;
    BOOL userInteractionEnabled = NO;
    if (orderSwitchTecNodeTypes.count > 1 && showBtn) {
        image = [UIImage imageNamed:kButtonImageName];
        userInteractionEnabled = YES;
    }
    [self.tecBars enumerateObjectsUsingBlock:^(HACTecInfoBar * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //            obj.titleButton.imageView.hidden = YES;//<=ios9 not work
        [obj.titleButton setImage:image forState:UIControlStateNormal];
        obj.titleButton.userInteractionEnabled = userInteractionEnabled;
    }];
}

- (HACTecType)nextTecTypeWithNowType:(HACTecType)nowType {
    HACTecType nextType = nowType;
    if (self.orderSwitchTecNodeTypes.count > 1) {
        NSUInteger __block index = 0;
        [self.orderSwitchTecNodeTypes enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.integerValue == nowType) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index == self.orderSwitchTecNodeTypes.count - 1) {
            index = 0;
        } else {
            index += 1;
        }
        if (index < self.orderSwitchTecNodeTypes.count) {
            nextType = self.orderSwitchTecNodeTypes[index].integerValue;
        }
    }
    return nextType;
}

- (void)setTecParamDic:(NSDictionary<NSNumber *,NSArray<NSNumber *> *> *)tecParamDic {
    if (tecParamDic.allKeys.count > 0) {
        [_tecParamDic removeAllObjects];
        [tecParamDic enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key, NSArray<NSNumber *> * _Nonnull obj, BOOL * _Nonnull stop) {
            [self->_tecParamDic setObject:obj forKey:key];
        }];
        [self.nodeDic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, HACChartNode * _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[HACTecNode class]]) {
                HACTecNode *tecNode = (HACTecNode *)obj;
                NSArray *tecParam = self->_tecParamDic[@(tecNode.tecType)];
                [tecNode setTec:tecNode.tecType withParam:tecParam];
            }
        }];
    }
}

- (void)setIsSoildFill:(BOOL)isSoildFill {
    _isSoildFill = isSoildFill;
    [self.nodeDic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, HACChartNode * _Nonnull node, BOOL * _Nonnull stop) {
        node.isSoildFill = isSoildFill;
    }];
}

- (void)setTec:(HACTecType)tecType withParam:(NSArray<NSNumber *> *)param {
    if (param) {
        [_tecParamDic setObject:param forKey:@(tecType)];
        [self.nodeDic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, HACChartNode * _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[HACTecNode class]]) {
                HACTecNode *tecNode = (HACTecNode *)obj;
                if (tecNode.tecType == tecType) {
                    NSArray *tecParam = self->_tecParamDic[@(tecNode.tecType)];
                    [tecNode setTec:tecNode.tecType withParam:tecParam];
                }
            }
        }];
    }
}

- (NSDictionary<NSNumber *,NSArray<NSNumber *> *> *)tecParamDic {
    return _tecParamDic;
}

//切换指定幅图type，node：指定幅图，index：幅图所对应的序号（第N个幅图）
- (void)orderSwitchTecNode:(HACTecNode*)node withIndex:(NSInteger)index {
    if (index < self.tecBars.count && index < self.tecNodeTypes.count) {
        HACTecType oldType = node.tecType;
        HACTecType newType = [self nextTecTypeWithNowType:oldType];
        [node setTecType:newType];
        NSArray *tecParam = _tecParamDic[@(newType)];
        if (tecParam.count > 0) {
            [node setTec:newType withParam:tecParam];
        }
        node.isSoildFill = self.isSoildFill;
        [node setNeedsDisplay];
        
        HACTecInfoBar *tecBar = [self.tecBars objectAtIndex:index];
        [self updateTecBar:tecBar withType:node.tecType];
        
        NSMutableArray *tmp = [NSMutableArray arrayWithArray:self.tecNodeTypes];
        [tmp replaceObjectAtIndex:index withObject:@(newType)];
        _tecNodeTypes = tmp;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(tecChangeNodeComponent:withIndex:oldType:newType:)]) {
            [self.delegate tecChangeNodeComponent:self withIndex:index oldType:oldType newType:newType];
        }
    }
    
}

- (HACTecInfoBar*)createTecBarWithTecType:(HACTecType)type {
    HACTecInfoBar *bar = [[HACTecInfoBar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, kTecBarHeight)];
    if (self.orderSwitchTecNodeTypes.count <= 1) {
        bar.titleButton.imageView.hidden = YES;
        [bar.titleButton setImage:nil forState:UIControlStateNormal];
    }
    [bar.titleButton addTarget:self action:@selector(tecButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self updateTecBar:bar withType:type];
    return bar;
}

- (void)updateTecBar:(HACTecInfoBar*)bar withType:(HACTecType)type {
    switch (type) {
        case HACTecTypeVolume: {
            [bar.titleButton setTitle:@"成交量" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"VOL: --"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeAmount: {
            [bar.titleButton setTitle:@"成交额" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"Amount: --"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeMACD: {
            [bar.titleButton setTitle:@"MACD" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"DIF:-- DEA:-- MACD:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeKDJ: {
            [bar.titleButton setTitle:@"KDJ" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"K:-- D:-- J:-- KDJ(,,)"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeRSI: {
            [bar.titleButton setTitle:@"RSI" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"RSI1:-- RSI2:-- RSI3:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeBOLL: {
            [bar.titleButton setTitle:@"BOLL" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"MID:-- UPPER:-- LOWER:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypePSY: {
            [bar.titleButton setTitle:@"PSY" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"PSY:-- PSYMA:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeOBV: {
            [bar.titleButton setTitle:@"OBV" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"OBV:-- OBVMA:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeDMI: {
            [bar.titleButton setTitle:@"DMI" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"PDI:-- MDI:-- ADX:-- ADXR:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeWR: {
            [bar.titleButton setTitle:@"WR" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"WR1:-- WR2:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeASI: {
            [bar.titleButton setTitle:@"ASI" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"ASI:-- ASIMA:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeDMA: {
            [bar.titleButton setTitle:@"DMA" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"DDD:-- AMA:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeBIAS: {
            [bar.titleButton setTitle:@"BIAS" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"BIAS1:-- BIAS2:-- BIAS3:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeVR: {
            [bar.titleButton setTitle:@"VR" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"VR:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
        case HACTecTypeCCI: {
            [bar.titleButton setTitle:@"CCI" forState:UIControlStateNormal];
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"CCI:--"];
            [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attriStr.length)];
            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:kBarInfoFont] range:NSMakeRange(0, attriStr.length)];
            bar.infoString = attriStr;
            break;
        }
    }
    // button image居右
    bar.titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, -bar.titleButton.imageView.bounds.size.width-8, 0, bar.titleButton.imageView.bounds.size.width);
    bar.titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, bar.titleButton.titleLabel.bounds.size.width, 0, -bar.titleButton.titleLabel.bounds.size.width);
}

- (void)tecButtonClick:(UIButton*)sender {
    if ([self.delegate respondsToSelector:@selector(tecButtonTouchedNodeComponent:withIndex:)]) {
        [self.delegate tecButtonTouchedNodeComponent:self withIndex:sender.tag];
    }
}

- (void)refreshTecbarInfoAtIndex:(NSInteger)index {
    //update tecbars
    for (int i = 0; i < self.tecNodeTypes.count; i++) {
        HACTecNode *node;
        HACTecInfoBar *tecbar = i<self.tecBars.count?self.tecBars[i]:nil;
        NSString *nodeKey = [NSString stringWithFormat:@"%@%d", HACNodesComponentTecNodeKey, i];
        if ((node = (HACTecNode *)self.nodeDic[nodeKey]) && tecbar) {
            NSAttributedString *tecInfo = [node stringAtChartForIndex:index];
            tecbar.infoString = tecInfo;
        }
    }
}

#pragma mark -- tap:顺序切换
- (void)reactForTapGesture:(UITapGestureRecognizer *)gesture {
    [super reactForTapGesture:gesture];
    CGPoint point = [gesture locationInView:self];
    [self.nodeDic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, HACChartNode * _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[HACTecNode class]]) {
            if (CGRectContainsPoint(obj.relativeFrame, point)) {
                NSString *indexStr = [key substringFromIndex:key.length-1];
                [self orderSwitchTecNode:(HACTecNode *)obj withIndex:indexStr.integerValue];
                *stop = YES;
            }
        }
    }];
}
@end

